package com.cloud.security.handler;

import com.cloud.enums.SecurityEnum;
import com.cloud.exception.ValidateException;
import com.cloud.pojo.sys.Result;
import com.cloud.util.SecurityHandlerUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败处理逻辑
 */
@Component
public class CustomizeAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        if(e.getCause() instanceof ValidateException) {
            ValidateException exception = (ValidateException)e.getCause();
            SecurityHandlerUtil.responseHandler(response, Result.createFail(SecurityEnum.LOGIN_VALIDATE_FAILURE.getCode(), exception.getErrorMsg()));
        }else {
            SecurityHandlerUtil.responseHandler(response, Result.createFail(SecurityEnum.LOGIN_VALIDATE_FAILURE.getCode(), SecurityEnum.LOGIN_VALIDATE_FAILURE.getDesc()));
        }
    }
}
